package com.xyz.gate.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.xyz.gate.common.R;
import com.xyz.gate.service.WhitelistUrl;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 验证访问者是否具有接口的访问权限
 */
public class PermissionFilter extends ZuulFilter {

    @Resource
    WhitelistUrl whitelistUrl;

    /**
     * 是否应该执行该过滤器，如果是false，则不执行该filter
     */
    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        if(!ctx.sendZuulResponse()){
            return false;
        }
        return true;
    }

    /**
     * 过滤器类型
     * 顺序: pre ->routing -> post ,以上3个顺序出现异常时都可以触发error类型的filter
     */
    @Override
    public String filterType() {

        return FilterConstants.PRE_TYPE;
    }

    /**
     * 同filterType类型中，order值越大，优先级越低
     */
    @Override
    public int filterOrder() {

        return 1000;
    }


    /**
     * 执行业务操作，可执行sql,nosql等业务
     */
    @Override
    public Object run() {


        //拦截所有请求
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        if (!whitelistUrl.isNeedLogin(request.getRequestURI())) {
            return null;
        }


        String requestURL = request.getRequestURL().toString();

        //此处根据用户id 及请求url查询数据库查看该用户是否具有接口的访问权限，没有则拒绝
        String userName2 = request.getAttribute("userName").toString();

        if (requestURL.contains("aaa")) {
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            ctx.getResponse().setCharacterEncoding("UTF-8");
            ctx.getResponse().setContentType("application/json");
            try {
                ctx.getResponse().getWriter().write(R.error("你没有访问该接口的权限！！").toString());
            } catch (Exception e) {
            }
        }

        return null;
    }
}
